<template>
  <div id="rate" @touchmove="onTouchMove">
    <md-icon v-for="(value,index) in list" :key="index" :name="value?iconName:uniconName" :class="iconName" :data-index="index" @click="onSelect(index)"></md-icon>
  </div>
</template>

<script>
import '@/assets/svgs/star.svg';
import '@/assets/svgs/star_big.svg';
import '@/assets/svgs/unstar.svg';
import '@/assets/svgs/unstar_big.svg';
import { Icon } from 'mand-mobile';
export default {
  name: 'rate',
  components: {
    [Icon.name]: Icon
  },
  props: {
    readonly: Boolean,
    disabled: Boolean,
    value: {
      type: Number,
      default: 0
    },
    count: {
      type: Number,
      default: 5
    },
    size: {
      type: String,
      default: 'small'
    }
  },
  methods: {
    onSelect(index) {
      if (!this.disabled && !this.readonly) {
        this.$emit('input', index + 1);
        this.$emit('change', index + 1);
        this.value = index + 1;
      }
    },
    onTouchMove(event) {
      if (!document.elementFromPoint) {
        return;
      }
      event.preventDefault();
      const { clientX, clientY } = event.touches[0];
      const target = document.elementFromPoint(clientX, clientY);
      if (target && target.dataset) {
        const { index } = target.dataset;
        /* istanbul ignore else */
        if (index) {
          this.onSelect(+index);
        }
      }
    }
  },
  computed: {
    list() {
      return Array.apply(null, {
        length: this.count
      }).map((value, index) => index < this.value);
    },
    iconName() {
      if (this.size === 'small') {
        return 'star';
      } else {
        return 'star_big';
      }
    },
    uniconName() {
      if (this.size === 'small') {
        return 'unstar';
      } else {
        return 'unstar_big';
      }
    }
  }
};
</script>

<style lang="stylus" scoped>
#rate {
  .star {
    width: 24px;
    height: 24px;
  }

  .star_big {
    width: 68px;
    height: 68px;
    margin: 0px 10px;
  }

  .unstar {
    width: 24px;
    height: 24px;
  }

  .unstar_big {
    width: 68px;
    height: 68px;
    margin: 0px 10px;
  }
}
</style>
